package com.zuoshenge.main.controller;

import com.zuoshenge.bean.JwtProperties;
import com.zuoshenge.expection.BadRequestException;
import com.zuoshenge.main.bean.MyStudentDetails;
import com.zuoshenge.main.dto.UserRequestDTO;
import com.zuoshenge.main.entity.Student;
import com.zuoshenge.main.service.EmailService;
import com.zuoshenge.main.service.MyUserDetailService;
import com.zuoshenge.main.service.OnlineUserService;
import com.zuoshenge.main.service.StudentDataService;
import com.zuoshenge.redis.util.RedisUtil;
import com.zuoshenge.util.JwtTokenUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/auth")
public class AuthController {

    @Resource
    private JwtTokenUtil jwtTokenUtil;
    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    private JwtProperties jwtProperties;
    @Resource
    private StudentDataService studentDataService;
    @Resource
    private MyUserDetailService myUserDetailService;
    @Resource
    private OnlineUserService onlineUserService;
    @Resource
    private EmailService emailService;
    @Resource
    private RedisUtil redisUtil;

    private final static String EMAIL_CODE_KEY = "email-code:";

    @PostMapping("/student-login")
    public ResponseEntity<Object> StudentLogin(@RequestBody UserRequestDTO userRequestDTO) {
        UserDetails userDetails = myUserDetailService.loadUserByUsername(userRequestDTO.getSid());
        if (!passwordEncoder.matches(userRequestDTO.getPassword(), userDetails.getPassword())) {
            Map<String, Object> errorDetails = new HashMap<>();
            errorDetails.put("msg", "用户名或密码错误");
            errorDetails.put("status", 0); // 注意：你可能需要添加一个方法来获取这个值
            return ResponseEntity.ok(errorDetails);
        }
        Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails, userRequestDTO.getPassword(), userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authentication);
        String jwt = jwtTokenUtil.generateToken(authentication);
        Student student = studentDataService.queryStudentBySid(userRequestDTO.getSid());
        System.out.println("生成的token:" + jwtProperties.getTokenStartWith() + jwt);

        Map<String, Object> result = new HashMap<>(9);
        result.put("token", jwtProperties.getTokenStartWith() + jwt);
        result.put("sid", student.getSid());
        result.put("msg", "登录成功");
        result.put("status", 1);

        onlineUserService.saveStudent(student, jwt);
        return ResponseEntity.ok(result);
    }

    @PostMapping("/student-register")
    public ResponseEntity<Object> StudentRegister(@RequestBody Student student) {
        Map<String, Object> result = new HashMap<>();
        if (studentDataService.queryStudentBySid(student.getSid()) != null) {
            result.put("status", 0);
            result.put("msg", "学生已经存在");
        } else {
            student.setPassword(passwordEncoder.encode(student.getPassword()));
            studentDataService.addStudent(student);
            result.put("status", 1);
            result.put("msg", "学生信息录入成功");
        }

        return ResponseEntity.ok(result);
    }

    @GetMapping("/send-code")
    public ResponseEntity<Object> sendCode(@RequestParam String sid) {
        Map<String, Object> result = new HashMap<>();
        Student student = studentDataService.queryStudentBySid(sid);
        if (student != null) {
            // 生成6位数字的验证码
            StringBuilder x = new StringBuilder();
            for (int i = 0; i < 6; i++) {
                int digit = ThreadLocalRandom.current().nextInt(10); // 使用ThreadLocalRandom生成随机数
                x.append(digit);
            }
            String code = x.toString();
            String content = "验证码10分钟过期";
            String codeKey = EMAIL_CODE_KEY + student.getSid();
            redisUtil.set(codeKey, code, 10, TimeUnit.MINUTES);
            emailService.sendSimpleMail(student.getEmail(), "验证码"+code, content);
        }
        result.put("status", 1);
        result.put("msg", "发送成功");
        return ResponseEntity.ok(result);
    }

    @GetMapping("/check-code")
    public ResponseEntity<Object> checkCode(@RequestParam String sid, @RequestParam String code){
        String codeKey = EMAIL_CODE_KEY + sid;
        String redisCode = (String)redisUtil.get(codeKey);
        Map<String, Object> result = new HashMap<>();
        if (StringUtils.isBlank(redisCode)) {
            result.put("msg", "redis无该用户的验证码，可能原因：用户验证码过期 或者 用户名错误");
            result.put("status", -1);
        } else {
            if (!redisCode.equals(code)) {
                result.put("msg", "用户验证码错误");
                result.put("status", 0);
            } else {
                result.put("msg", "验证码正确！");
                result.put("status", 1);
                redisUtil.del(codeKey);
            }
        }
        return ResponseEntity.ok(result);
    }
}
